
SOUNDOFF_SavedVars = {};

local RECENT_SOUNDS = {};
local RECENT_MAX   = 11;

local _VERSION_ = "1.0"

local o_PlaySound;

local function GetSavedVar(name,def)
	local key = GetRealmName() .. "_" .. UnitName("player") .. "_" .. name;
	if (SOUNDOFF_SavedVars[key] ~= nil) then
		return SOUNDOFF_SavedVars[key];
	end
	return def;
end

local function SetSavedVar(name,val)
	local key = GetRealmName() .. "_" .. UnitName("player") .. "_" .. name;
	SOUNDOFF_SavedVars[key] = val;
end

local function override_PlaySound(sound)
	local offTab = GetSavedVar("OFF_TAB",{})
	if offTab[sound] ~= nil then
		-- do nothing
	else
		o_PlaySound(sound)
	end
	table.insert(RECENT_SOUNDS,0,sound)
	table.insert(RECENT_SOUNDS,0,time())
	while #RECENT_SOUNDS > (RECENT_MAX*2) do
		table.remove(RECENT_SOUNDS)
		table.remove(RECENT_SOUNDS)
	end
end

local function SoundOff_SetupButtons(sndFrame)
	local i = 0
	for i = 0, RECENT_MAX-1, 1 do
		local btn = getglobal(sndFrame:GetName() .. "_Recent" .. "_SoundBtn" .. (i+1))
		local btn_text = getglobal(btn:GetName() .. "Text")
		local listoffset = (i*2)
		if (#RECENT_SOUNDS/2) > i then
			btn:Show()
			btn.soundname = RECENT_SOUNDS[listoffset+1]
			btn_text:SetText(btn.soundname .. "  played " .. difftime(time(),RECENT_SOUNDS[listoffset]) .. " seconds(s) ago")
			local offTab = GetSavedVar("OFF_TAB",{})
			if offTab[btn.soundname] ~= nil then
				btn:SetChecked(1)
			else
				btn:SetChecked(0)
			end
		else
			btn:Hide()
		end
	end
end

local function SoundOff_SlashCmd(cmd)
	local frame = getglobal("SoundOff")
	if not frame:IsVisible() then
		frame:Show()
	else
		frame:Hide()
	end
end

function SoundOff_Btn_Click(btn)
	if btn.soundname ~= nil then
		local offTab = GetSavedVar("OFF_TAB",{})
		if offTab[btn.soundname] ~= nil then
			DEFAULT_CHAT_FRAME:AddMessage("Sound " .. btn.soundname .. " ON")
			offTab[btn.soundname] = nil
		else
			DEFAULT_CHAT_FRAME:AddMessage("Sound " .. btn.soundname .. " OFF")
			offTab[btn.soundname] = 1
		end
		SetSavedVar("OFF_TAB",offTab)
	end
end

function SoundOff_ShowOffList()
	RECENT_SOUNDS = {}
	local offTab = GetSavedVar("OFF_TAB",{})
	for k,v in pairs(offTab) do
		if v ~= nil then
			table.insert(RECENT_SOUNDS,0,k)
			table.insert(RECENT_SOUNDS,0,time())
		end
	end
	local frame = getglobal("SoundOff")
	SoundOff_SetupButtons(frame)
end

function SoundOff_Hide()
	local frame = getglobal("SoundOff")
	frame:Hide()
end

function SoundOff_OnShow(self)
	SoundOff_SetupButtons(self)
end

function SoundOff_OnHide(self)
end

function SoundOff_Load(self)
	SlashCmdList["SOUNDOFF"] = SoundOff_SlashCmd;
	SLASH_SOUNDOFF1 = "/soundoff" 
	SLASH_SOUNDOFF2 = "/sndoff" 

	DEFAULT_CHAT_FRAME:AddMessage("SoundOff loaded! ver " .. _VERSION_,0.5,0,5,1);
	DEFAULT_CHAT_FRAME:AddMessage("/soundoff or /sndoff to bring up configuration.");
	o_PlaySound = PlaySound;
	PlaySound = override_PlaySound;
end
